<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body style="width: 100%;height: 100%">

</iframe>
<div id="printcontent" style="width: 1200px;height: 100%;margin: 100px auto">
    <p th:text="${content}" style="text-align: justify;text-indent: 2em"></p>
    <img src="https://www.shicimingju.com/pics/item/2973.jpg" alt="">
    <a style="margin-left: 200px;font-size: 30px;color: red" href="javascript:void(0);" class="dayin">-->打印</a>

</div>

<script>
    $(function () {
        $('.dayin').click(function () {
            doPrint3()
        })
    })

    function doPrint3() {
        //判断iframe是否存在，不存在则创建iframe
        var iframe = document.getElementById("print-iframe");
        if (!iframe) {
            var el = document.getElementById("printcontent");
            iframe = document.createElement('IFRAME');
            var doc = null;
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            //这里可以自定义样式
            //doc.write("<LINK rel="stylesheet" type="text/css" href="css/print.css">");
            doc.write("<title>我是title头部信息啊！！！</title>");
            doc.write('<div>' + el.innerHTML + '</div>');
            doc.close();
            iframe.contentWindow.focus();
        }
        iframe.contentWindow.print();
        if (navigator.userAgent.indexOf("MSIE") > 0) {
            document.body.removeChild(iframe);
        }
    }
</script>
</body>
</html>
